from transformers import ViTFeatureExtractor, ViTPreTrainedModel, ViTConfig, ViTModel
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
from torch import nn
from typing import Dict, List, Optional, Set, Tuple, Union
import torch

from transformers.modeling_outputs import ImageClassifierOutput
from transformers.utils import ModelOutput
from dataclasses import dataclass


@dataclass
class ImageClassifierOutput2(ModelOutput):
    
    loss: Optional[torch.FloatTensor] = None
    logits1: torch.FloatTensor = None
    logits2: torch.FloatTensor = None
    hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
    attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
    
    
class ViTForImageClassification(ViTPreTrainedModel):
    def __init__(self, config: ViTConfig) -> None:
        super().__init__(config)
        self.ratio       = [0.05, 0.95]
        self.num_labels1 = config.num_labels1
        self.num_labels2 = config.num_labels2
        self.vit = ViTModel(config, add_pooling_layer=False)

        # Classifier head
        self.classifier1 = nn.Linear(config.hidden_size, config.num_labels1) if config.num_labels1 > 0 else nn.Identity()
        self.classifier2 = nn.Linear(config.hidden_size, config.num_labels2) if config.num_labels2 > 0 else nn.Identity()

        # Initialize weights and apply final processing
        self.post_init()

    
    def forward(
        self,
        pixel_values: Optional[torch.Tensor] = None,
        head_mask: Optional[torch.Tensor] = None,
        labels1: Optional[torch.Tensor] = None,
        labels2: Optional[torch.Tensor] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        interpolate_pos_encoding: Optional[bool] = None,
        return_dict: Optional[bool] = None,
    ) -> Union[tuple, ImageClassifierOutput]:
        r"""
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
        """
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        outputs = self.vit(
            pixel_values,
            head_mask=head_mask,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            interpolate_pos_encoding=interpolate_pos_encoding,
            return_dict=return_dict,
        )

        sequence_output = outputs[0]

        logits1 = self.classifier1(sequence_output[:, 0, :])
        logits2 = self.classifier2(sequence_output[:, 0, :])
        loss = None
        
        if labels1 is not None:
            # move labels to correct device to enable model parallelism
            labels1 = labels1.to(logits1.device)
            if self.config.problem_type is None:
                if self.num_labels == 1:
                    self.config.problem_type = "regression"
                elif self.num_labels > 1 and (labels1.dtype == torch.long or labels1.dtype == torch.int):
                    self.config.problem_type = "single_label_classification"
                else:
                    self.config.problem_type = "multi_label_classification"

            if self.config.problem_type == "regression":
                loss_fct = MSELoss()
                if self.num_labels == 1:
                    loss1 = loss_fct(logits1.squeeze(), labels1.squeeze())
                else:
                    loss1 = loss_fct(logits1, labels1)
            elif self.config.problem_type == "single_label_classification":
                loss_fct = CrossEntropyLoss()
                loss1 = loss_fct(logits1.view(-1, self.num_labels1), labels1.view(-1))
            elif self.config.problem_type == "multi_label_classification":
                loss_fct = BCEWithLogitsLoss()
                loss1 = loss_fct(logits1, labels1)
        
        if labels2 is not None:
            # move labels to correct device to enable model parallelism
            labels2 = labels2.to(logits2.device)
            if self.config.problem_type is None:
                if self.num_labels == 1:
                    self.config.problem_type = "regression"
                elif self.num_labels > 1 and (labels2.dtype == torch.long or labels2.dtype == torch.int):
                    self.config.problem_type = "single_label_classification"
                else:
                    self.config.problem_type = "multi_label_classification"

            if self.config.problem_type == "regression":
                loss_fct = MSELoss()
                if self.num_labels == 1:
                    loss2 = loss_fct(logits2.squeeze(), labels2.squeeze())
                else:
                    loss2 = loss_fct(logits2, labels2)
            elif self.config.problem_type == "single_label_classification":
                loss_fct = CrossEntropyLoss()
                loss2 = loss_fct(logits2.view(-1, self.num_labels2), labels2.view(-1))
            elif self.config.problem_type == "multi_label_classification":
                loss_fct = BCEWithLogitsLoss()
                loss2 = loss_fct(logits2, labels2)
        loss = loss1*self.ratio[0] + loss2*self.ratio[1]
        
        if not return_dict:
            output = (logits1, logits2) + outputs[1:]
            return ((loss,) + output) if loss is not None else output

        return ImageClassifierOutput2(
            loss=loss,
            logits1=logits1,
            logits2=logits2,
            hidden_states=outputs.hidden_states,
            attentions=outputs.attentions,
        )